package com.neomanager.login.web;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import sun.misc.BASE64Encoder;

import com.util.SHA256;
import com.neomanager.login.dao.LoginDao;
import com.neomanager.login.model.AdminInfo;

@Controller
@SuppressWarnings("restriction")
@SessionAttributes("adminInfo")
public class LoginController
{
	private final Logger logger = Logger.getLogger(this.getClass());
	@Resource(name="LoginDao")
	LoginDao login;

	/**
	 * 로그인 화면
	 */
	@RequestMapping(value = "/login/login.do", method = RequestMethod.GET)
	public String formLogin(Model model)
	{
		logger.info("로그인 화면.");

		return "login/login";
	}

	/**
	 * 로그인 처리
	 * @param response
	 */
	@RequestMapping(value = "/login/login_proc.do", method = RequestMethod.POST)
	public String processLogin(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response
			)  throws Exception
	{
		String alertMsg = "";		// alert 메세지
		String gotoUrl = null;		// 이동페이지 디폴트는 history.go(-1)

		// 비밀번호 암호화
		String pw = commandMap.get("pw").toString();
		SHA256 s = new SHA256( pw.getBytes() );
		BASE64Encoder Base64Encoder = new BASE64Encoder();
		pw = Base64Encoder.encode(s.GetHashCode());
		commandMap.put("pw", pw);

		logger.info("로그인 처리.");

		HttpSession session = request.getSession(true);
		AdminInfo adminInfo = login.selectAdminInfo( commandMap );
		if (adminInfo == null)
		{
			alertMsg = "아이디 또는 비밀번호 오류입니다..";
			model.addAttribute("alertMsg", alertMsg);
			model.addAttribute("gotoUrl", gotoUrl);
			return "common/alert";
		}
		/*else
		{
			session.setMaxInactiveInterval(60 * 60 * 60); 
			session.setAttribute("adminInfo", adminInfo);
		}*/

		model.addAttribute("adminInfo", adminInfo);
		String url = "../admin/adminmng_list.do";
		if (!adminInfo.getAdmin_gubun().equals("1"))
		{
			Map<String, Object> rsMap = login.selectAdminPage( commandMap );
			url = rsMap.get("MENU_URL").toString();
		}

		//최종 로그인 업데이트
		login.updateLastLogin(adminInfo.getSys_id());
		
		return "redirect:"+url;
	}

	/**
	 * 로그아웃
	 */
	@RequestMapping(value = "/login/logout.do", method = RequestMethod.GET)
	public String processLogout(Model model)
	{
		logger.info("로그아웃");
		model.addAttribute("adminInfo", new AdminInfo());

		return "login/login";
	}

}
